package com.linjiahao.nettyOne.server;

import com.alibaba.fastjson.JSON;
import com.linjiahao.nettyOne.handler.ChannelHandlerPool;
import com.linjiahao.servicebase.common.RabbitPublisher;
import com.linjiahao.servicebase.common.RedisService;
import com.linjiahao.servicebase.vo.NettyMessageVO;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelId;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.UUID;

/**
 * @ClassName SendMessage
 * @Description: 封装发送消息工具类
 * @Author linjiahao
 * @Date 10/1/2022
 **/
@Component
@Slf4j
public class SendMessage {

    @Resource
    private RedisService redisService;

    @Resource
    private RabbitPublisher rabbitPublisher;

    public void send(ChannelHandlerContext ctx, NettyMessageVO nettyMessageVO,Boolean isMqMessage) throws UnknownHostException {
        String receiverId = String.valueOf(nettyMessageVO.getReceiveId());
        //查询当前节点是否有改接收者通道
        Object channleId = redisService.hget(ChannelHandlerPool.channelUserKey, receiverId);
        if(channleId ==null){
            log.info("{}用户离线,消息id为：{}",nettyMessageVO.getReceiveId(),nettyMessageVO.getMessageId());
            return;
        }
        Channel channel = ChannelHandlerPool.channelGroup.find((ChannelId)channleId);
        if(channel!=null){
            InetAddress address = InetAddress.getLocalHost();
            log.info("接收用户{},在当前节点：{}",receiverId,address);
            if(isMqMessage){
                log.info("消费成功,消息id为：{}",nettyMessageVO.getMessageId());
                redisService.hdel(ChannelHandlerPool.userMessageKey,nettyMessageVO.getReceiveId());
            }
            channel.writeAndFlush(new TextWebSocketFrame(JSON.toJSONString(nettyMessageVO)));
        }else {
            if(isMqMessage){
                log.info("消费成功,目标不在本节点,消息id为：{}",nettyMessageVO.getMessageId());
                return;
            }
            log.info("接收用户不在在当前节点，进行mq广播：{}",receiverId);
            //设置离线消息，其他节点存在就会删除
            redisService.hset(ChannelHandlerPool.userMessageKey,receiverId, JSON.toJSONString(nettyMessageVO));
            rabbitPublisher.send(JSON.toJSONString(nettyMessageVO));
        }
    }
}
